package com.plumecache.core.interceptor;

import com.plumecache.core.CacheService;
import com.plumecache.core.annotation.CacheVersion;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Method;
import java.util.Map;

public class VersionCacheInterceptor extends BaseCacheInterceptor {

    @Override
    public Integer getOrder() {
        return Integer.MIN_VALUE;
    }

    @Override
    public boolean preHandle(CacheService target, Method method, Object[] args, Map<String, Object> context) {
        Object value = getValue(method, args);

        Class<?> clazz = (Class<?>) getValueClazz(method, args);
        if (null == clazz && value != null) {
            clazz = value.getClass();
        }

        if (null == clazz) {
            return true;
        }

        if (!clazz.isAnnotationPresent(CacheVersion.class)) {
            return true;
        }

        String version = clazz.getAnnotation(CacheVersion.class).value();

        if (StringUtils.isBlank(version)) {
            return true;
        }

        String newKey = getKey(method, args).concat("@").concat(version);
        setKey(method, args, newKey);
        return true;
    }


}
